/*
 *
 *  *    Copyright 2020-2021 Luter.me
 *  *
 *  *    Licensed under the Apache License, Version 2.0 (the "License");
 *  *    you may not use this file except in compliance with the License.
 *  *    You may obtain a copy of the License at
 *  *
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  *    Unless required by applicable law or agreed to in writing, software
 *  *    distributed under the License is distributed on an "AS IS" BASIS,
 *  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  *    See the License for the specific language governing permissions and
 *  *    limitations under the License.
 *
 */

package com.luter.heimdall.core.config;

import org.slf4j.Logger;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.representer.Representer;

import java.io.IOException;
import java.io.InputStream;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * 配置文件管理
 *
 * @author luter
 */
public abstract class ConfigManager {
    private static final transient Logger log = getLogger(ConfigManager.class);
    /**
     * The constant config.
     */
    private static volatile HeimdallProperties config;

    /**
     * The constant CONFIG_FILE_NAME.配置文件默认名称
     */
    private static final String CONFIG_FILE_NAME = "heimdall-config";

    private ConfigManager() {
    }

    /**
     * 设置全局配置
     *
     * @param customConfig the config
     */
    public static void setConfig(HeimdallProperties customConfig) {
        config = customConfig;
    }

    /**
     * 获取全局配置
     *
     * @return the config
     */
    public synchronized static HeimdallProperties getConfig() {
        if (null == config) {
            synchronized (ConfigManager.class) {
                if (null == config) {
                    setConfig(parserConfig());
                    log.debug("[getConfig]::Configuration loaded successfully.\n{}", config.toString());
                }
            }
        }
        return config;
    }

    /**
     * Parser config auth way properties.
     *
     * @return the auth way properties
     */
    private static HeimdallProperties parserConfig() {
        Yaml yaml = createYaml();
        InputStream inputStream = null;
        try {
            String fileName = CONFIG_FILE_NAME + ".yaml";
            inputStream = ConfigManager.class.getClassLoader().getResourceAsStream(fileName);
            if (null == inputStream) {
                fileName = CONFIG_FILE_NAME + ".yml";
                inputStream = ConfigManager.class.getClassLoader().getResourceAsStream(fileName);
                if (null == inputStream) {
                    String error = "Config properties initialized failed.The configuration file  was not read correctly. " +
                            "Please Make sure that the correct configuration file " +
                            "named:[" + CONFIG_FILE_NAME + ".yaml or " + CONFIG_FILE_NAME + ".yml] exists in the classpath";
                    throw new IllegalArgumentException(error);
                }
            }
            log.info("Config  properties initialized successfully.file =[" + fileName + "]");
            return yaml.loadAs(inputStream, HeimdallProperties.class);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private static Yaml createYaml() {
        LoaderOptions loaderOptions = new LoaderOptions();
        //不允许 Key 重复
        loaderOptions.setAllowDuplicateKeys(false);
        Representer representer = new Representer();
        //跳过不存在的属性，数据套几层都行
        representer.getPropertyUtils().setSkipMissingProperties(true);
//        return new Yaml(representer);
        return new Yaml(loaderOptions);
    }
}
